using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;

namespace OpenWaves.EPiServer.AdminTools.LogViewer
{
    public class LogDirectory
    {
        private readonly string path;
        private IEnumerable<LogFile> files;

        public LogDirectory(string path)
        {
            Contract.Requires<ArgumentNullException>(String.IsNullOrEmpty(path) == false);
            Contract.Requires<DirectoryNotFoundException>(Directory.Exists(path));

            this.path = path;
        }

        public string Path
        {
            get { return this.path; }
        }

        public string Name
        {
            get { return System.IO.Path.GetFileName(path); }
        }

        public IEnumerable<LogFile> Files
        {
            get
            {
                if (files == null)
                {
                    files = LoadFiles();
                }
                return files;
            }
        }

        private IEnumerable<LogFile> LoadFiles()
        {
            return Directory.GetFiles(path)
                .Select(filePath => new LogFile(filePath))
                .OrderByDescending(file=>file.LastModified);
        }

        public bool TryGetFile(string fullPath, out LogFile file)
        {
            if(PathEquals(System.IO.Path.GetDirectoryName(fullPath),this.path)==false)
            {
                file = null;
                return false;
            }

            file =
                Files.SingleOrDefault(f =>PathEquals(f.Name,System.IO.Path.GetFileName(fullPath)));
            return file != null;
        }

        private static bool PathEquals(string path1, string path2)
        {
            return string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase);
        }
    }
}